package com.example.startapp.util;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

import com.example.startapp.entity.User;

import java.util.ArrayList;

public class DBOpenHelper extends SQLiteOpenHelper {
    private SQLiteDatabase db;

    public DBOpenHelper(@Nullable Context context) {
        super(context, "db_test", null, 1);
        db = getReadableDatabase();

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE IF NOT EXISTS user("
                + " id INTEGER PRIMARY KEY AUTOINCREMENT , "
                + " name  TEXT ," + " password TEXT, " + " type TEXT )" );
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS user");
        onCreate(db);
    }

    //添加记录
    public void add(String name, String password, String type) {
        db.execSQL("INSERT INTO user (name,password,type) VALUES(?,?,?) ",
                new Object[]{name, password, type});
    }



    public String registerData(String name) {

        Cursor cursor = db.query("user", null, "name=? and type=?", new String[]{name, "注册"}, null, null, null, null);

        cursor.moveToFirst();
        String getId = cursor.getString(cursor.getColumnIndex("id"));
        cursor.close();
        return getId;

    }

    public ArrayList<User> getAllData() {

        ArrayList<User> list = new ArrayList<User>();
        Cursor cursor = db.query("user", null, null, null, null, null, "name DESC");
        while (cursor.moveToNext()) {
            String name = cursor.getString(cursor.getColumnIndex("name"));
            String password = cursor.getString(cursor.getColumnIndex("password"));
            list.add(new User(name, password));
        }
        return list;
    }


}
